#include <iostream>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "udp_client.hpp"
using namespace std;

static void usage(std::string proc)
{
   std::cout<<"Usage:\n\t"<<proc<<"serverip serverport\n"<<std::endl;
}

int main(int argc,char* argv[])
{
   if(argc!=3)
   {
      usage(argv[0]);
      exit(USAGE_ERR);
   }
   std::string serverip = argv[1];
   uint16_t serverport = atoi(argv[2]);
   
    int sock = socket(AF_INET,SOCK_DGRAM,0);
    if(sock<0)
    {
         std::cerr << "create socket error" << std::endl;
         exit(SOCKET_ERR);
    }
   struct sockaddr_in server;
   memset(&server,0,sizeof(server));
   server.sin_family = AF_INET;
   server.sin_port = htons(serverport);
   server.sin_addr.s_addr = inet_addr(serverip.c_str());
   while(true)
   {
      std::string message;
      std::cout<<"[贵哥的服务器]#";

      std::getline(std::cin,message);

      sendto(sock,message.c_str(),message.size(),0,(struct sockaddr*)&server,sizeof(server));

      char buffer[2048];
      struct sockaddr_in temp;
      socklen_t len = sizeof(temp);
      int n = recvfrom(sock, buffer, sizeof(buffer)-1, 0, (struct sockaddr*)&temp, &len);
      if(n > 0)
        {
            buffer[n] = 0;
            std::cout <<  buffer << std::endl;
        }
   }

   return 0;
}